var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/businessComponent/Attachment/api.tsx
var api_exports = {};
__export(api_exports, {
  getAttachmentCountBatch: () => getAttachmentCountBatch,
  getTableAttachmentApi: () => getTableAttachmentApi,
  openAttachment: () => openAttachment,
  openFormTableAttachment: () => openFormTableAttachment
});
module.exports = __toCommonJS(api_exports);
var import_react = __toESM(require("react"));
var import_functionalComponent = require("../../functionalComponent");
var import_util = require("../../util");
var import_service = require("./service");
var import_util2 = require("./util");
var import_views = require("./views");
var isDev = process.env.NODE_ENV === "development";
var titleMap = {
  View: "文件查看",
  Edit: "文件编辑",
  Preview: "文件预览"
};
var getShareValue = (sharedOne, sharedOneName) => {
  const shareValue = [];
  if (sharedOne && sharedOneName) {
    const sharedOneList = sharedOne.split(",");
    const sharedOneNameList = sharedOneName.split(",");
    if (sharedOneList.length === sharedOneNameList.length) {
      for (let i = 0; i < sharedOneList.length; i++) {
        shareValue.push({ label: sharedOneNameList[i], value: sharedOneList[i] });
      }
    }
  }
  return shareValue;
};
var getTableAttachmentApi = async (params, cancelId) => {
  var _a, _b;
  const {
    asrSessionGuid: propAsrSessionGuid = "",
    asrFill: propAsrFill,
    asrFillName: propAsrFillName,
    unitNo: propUnitNo,
    orgNo: propOrgNo,
    projectNo: propProjectNo,
    uCode: propUCode,
    asrTable: propAsrTable,
    asrCode: propAsrCode,
    asrAttachTable = "",
    busTypeCode: propBusTypeCode,
    busUrl,
    approved = 0,
    customOpenTab,
    onSave,
    bizCode,
    // for accept
    labelConfig
  } = params;
  const busTypeCode = propBusTypeCode || ((_a = import_util.iup.getPageInstance()) == null ? void 0 : _a.busType);
  const openTab = typeof customOpenTab === "function" ? (title, path, params2) => customOpenTab(title, import_util.iup.handleUrl(path, params2)) : import_util2.openTab;
  const userInfo = import_util.iup.getUser();
  const asrFill = propAsrFill ?? userInfo.userNo;
  const asrFillName = propAsrFillName ?? userInfo.userName;
  const unitNo = propUnitNo ?? userInfo.tenantNo;
  const orgNo = propOrgNo ?? userInfo.orgNo;
  const projCode = propProjectNo ?? userInfo.projCode;
  const uCode = propUCode ?? userInfo.ucode;
  const getTableAttachInfo = async () => await (0, import_service.tableAttachInit)(
    {
      orgNo,
      tag: propAsrTable,
      busiIds: propAsrSessionGuid,
      unitNo,
      projCode,
      bizCode: bizCode || propBusTypeCode
    },
    cancelId
  );
  const tableAttachInfo = await getTableAttachInfo() || {};
  const asrSessionGuid = tableAttachInfo == null ? void 0 : tableAttachInfo.cursorId;
  const asrTable = propAsrTable || asrSessionGuid;
  const asrCode = propAsrCode || asrSessionGuid;
  const attachmentRecordList = ((_b = tableAttachInfo == null ? void 0 : tableAttachInfo.data) == null ? void 0 : _b.map((item) => {
    return {
      ...item,
      asrSessionGuid
    };
  })) ?? [];
  return {
    asrSessionGuid,
    asrFill,
    asrFillName,
    asrTable,
    asrCode,
    asrAttachTable,
    busTypeCode,
    orgNo,
    busUrl,
    uCode,
    tableAttachInfo,
    attachmentRecordList,
    labelConfig,
    getTableAttachInfo,
    handleEditOrView: async (file, type) => {
      const { asrName, asrFid, asrFill: asrFill2 } = file;
      const fileType = (0, import_util2.getFileType)(asrName);
      const url = "/WM/Archive/KingGridObject/KingGridObjectEdit";
      const params2 = {
        dbToken: uCode,
        RecordID: asrSessionGuid,
        BillId: asrFid,
        DataFrom: "attachment",
        AsrName: asrName,
        FileType: `.${fileType}`,
        OpType: type,
        BillBusinessType: busTypeCode
      };
      openTab(titleMap[type], url, params2);
    },
    handleDelete: async (id) => {
      const res = await (0, import_service.attachDelete)({
        fileIds: id,
        cursorId: asrSessionGuid
      });
      if ((res == null ? void 0 : res.code) === 0) {
        import_functionalComponent.message.success("删除成功");
        return true;
      } else {
        const msg = (res == null ? void 0 : res.message) || "删除失败";
        import_functionalComponent.message.error(msg);
      }
      return false;
    },
    handleDownload: async (files) => {
      var _a2;
      const filesArr = import_util.iup.isArray(files) ? files : [files];
      const fileIds = filesArr.map((file) => file.asrFid).join(",");
      const res = await (0, import_service.getDownloadFileUrl)({ fileId: fileIds });
      if ((res == null ? void 0 : res.code) === 0) {
        const downloadName = filesArr.length === 1 ? filesArr[0].asrName : Date.now();
        (0, import_util2.downloadFile)(downloadName, (_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.link, "url");
      }
    },
    handleZipDownload: async () => {
      const res = await (0, import_service.createZip)({
        busiIds: propAsrSessionGuid,
        tag: asrTable,
        orgNo,
        projCode,
        unitNo
      });
      if ((res == null ? void 0 : res.code) === 0) {
        const { data } = res;
        const getZipDownloadInfoLoop = async () => {
          const res2 = await (0, import_service.getZipDownloadInfo)({ id: data.id });
          if ((res2 == null ? void 0 : res2.code) === 0) {
            const { data: data2 } = res2;
            if (data2.pace < 100) {
              setTimeout(getZipDownloadInfoLoop, 2e3);
            } else {
              (0, import_util2.downloadFile)("package", data2["downloadUrl"], "url");
            }
          }
        };
        setTimeout(() => {
          getZipDownloadInfoLoop();
        }, 500);
      }
    },
    handlePreview: async (file) => {
      var _a2;
      const res = await (0, import_service.getPreviewUrl)({ fileId: file.asrFid });
      if ((res == null ? void 0 : res.code) === 0) {
        const url = (_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.link;
        openTab(titleMap.Preview, url);
      }
    },
    /**
     * @deprecated
     */
    handleEditCategory: async (checkedList) => {
      const res = await import_util.iup.external.openHelp({
        type: "SingleHelp",
        helpId: "AttachmentTypeHelpPlugin",
        valueField: "typeid",
        labelField: "typename",
        clientSqlFilter: `cuid=${tableAttachInfo.cuid}&bustypecode=${busTypeCode}`
      });
      if (res) {
        const editRes = await (0, import_service.editCategory)(
          {
            asrSessionGuid,
            asrFids: checkedList.map((item) => item.asrFid).join(","),
            typeId: res.value
          },
          uCode
        );
        if ((editRes == null ? void 0 : editRes.code) === 0) {
          import_functionalComponent.message.success("操作成功");
        }
      }
    },
    handleChangeShareType: async (v, data) => {
      const { asrFid, sharedOne, sharedOneName } = data;
      if (v === "self") {
        await (0, import_service.shareSave)(
          {
            asrSessionGuid,
            asrFid,
            sharedOne: asrFill,
            sharedOneName: asrFillName,
            shareType: v
          },
          uCode
        );
      } else {
        const helpTypeMap = {
          empno: "UserHelp",
          dept: "DeptHelp"
        };
        const helpType = helpTypeMap[v] || "UserHelp";
        const res = await import_util.iup.external.openHelp({
          type: helpType,
          multiple: true,
          value: getShareValue(sharedOne, sharedOneName)
        });
        if (res) {
          await (0, import_service.shareSave)(
            {
              asrSessionGuid,
              asrFid,
              sharedOne: res.map((item) => item.value).join(","),
              sharedOneName: res.map((item) => item.label).join(","),
              shareType: v
            },
            uCode
          );
        }
      }
    },
    handleValid: () => {
      return true;
    },
    handleSave: async (params2 = {}) => {
      const res = await (0, import_service.attachSave)([
        {
          cursorId: asrSessionGuid,
          tag: asrTable,
          unitNo,
          orgNo,
          projCode
        }
      ]);
      if ((res == null ? void 0 : res.code) === 0) {
        onSave == null ? void 0 : onSave(res == null ? void 0 : res.data);
        import_functionalComponent.message.success("保存成功");
      }
    }
  };
};
var getAttachmentCountBatch = async (params) => {
  const { asrCode, asrTable } = params;
  const res = await (0, import_service.getAttachmentCountBatch)({ asrCode, asrTable });
  return res;
};
var defaultAttachmentModalConfig = {
  title: "附件",
  width: 1e3,
  height: 700,
  footer: false
};
var openAttachment = (props) => new Promise((resolve) => {
  var _a, _b, _c, _d, _e;
  const { control = true, categoryStyle = {}, style = {}, ...restProps } = props;
  const apiRef = import_react.default.createRef();
  const getResult = async (closeStatus) => {
    var _a2, _b2;
    const api = ((_a2 = apiRef.current) == null ? void 0 : _a2.getApi()) ?? {};
    const result = await api.getResult();
    const isChanged = (_b2 = api == null ? void 0 : api.isChanged) == null ? void 0 : _b2.call(api);
    return {
      ...result,
      isChanged,
      closeStatus
    };
  };
  const handleOk = async (ins) => {
    var _a2, _b2, _c2;
    const api = ((_a2 = apiRef.current) == null ? void 0 : _a2.getApi()) ?? {};
    if (api.uploadingRef.current) {
      import_util.iup.message("正在上传中，无法关闭弹窗");
      return;
    }
    if ((_b2 = api.handleValid) == null ? void 0 : _b2.call(api)) {
      await (!control && ((_c2 = api == null ? void 0 : api.handleSave) == null ? void 0 : _c2.call(api)));
      const result = await getResult("ok");
      ins.destroy();
      resolve(result);
    }
  };
  const handleCancel = async (ins) => {
    const result = await getResult("cancel");
    ins.destroy();
    resolve(result);
  };
  (0, import_functionalComponent.showModal)({
    ...defaultAttachmentModalConfig,
    params: { isModal: true, handleOk, handleCancel },
    content: /* @__PURE__ */ import_react.default.createElement(
      import_views.TableAttachment,
      {
        fileTypeCode: (_e = (_d = (_c = (_b = (_a = import_util.iup.getPageInstance()) == null ? void 0 : _a.getGlobalState) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.attachmentProperty) == null ? void 0 : _d.sys_toolbar_column) == null ? void 0 : _e.fileTypeCode,
        ...restProps,
        style: { height: "100%", ...style },
        categoryStyle: {
          borderBottomLeftRadius: 10,
          ...categoryStyle
        },
        ref: apiRef
      }
    ),
    async onOk(ins) {
      await handleOk(ins);
    },
    async onCancel(ins) {
      await handleCancel(ins);
    }
  });
});
var openFormTableAttachment = (apis, props) => {
  return new Promise((resolve) => {
    const { control = true, labelConfig, modal } = props || {};
    const getResult = async (closeStatus) => {
      const api = apis ?? {};
      const result = await api.getResult();
      return {
        ...result,
        closeStatus
      };
    };
    const handleOk = async (ins) => {
      var _a, _b;
      const api = apis ?? {};
      if (api.uploadingRef.current) {
        import_util.iup.message("正在上传中，无法关闭弹窗");
        return;
      }
      if ((_a = api.handleValid) == null ? void 0 : _a.call(api)) {
        await (!control && ((_b = api == null ? void 0 : api.handleSave) == null ? void 0 : _b.call(api)));
        const result = await getResult("ok");
        ins.destroy();
        resolve(result);
      }
    };
    const handleCancel = async (ins) => {
      const result = await getResult("cancel");
      ins.destroy();
      resolve(result);
    };
    (0, import_functionalComponent.showModal)({
      ...defaultAttachmentModalConfig,
      useModal: modal,
      params: { isModal: true, handleOk, handleCancel },
      content: /* @__PURE__ */ import_react.default.createElement(
        import_views.OriginTableAttachment,
        {
          labelConfig,
          style: { height: "100%" },
          categoryStyle: {
            borderBottomLeftRadius: 10
          }
        }
      ),
      async onOk(ins) {
        await handleOk(ins);
      },
      async onCancel(ins) {
        await handleCancel(ins);
      }
    });
  });
};
import_util.iup.registerExternal({ openAttachment });
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  getAttachmentCountBatch,
  getTableAttachmentApi,
  openAttachment,
  openFormTableAttachment
});
